package ru.batrdmi.svnplugin.actions;

import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vcs.FilePath;
import org.jetbrains.annotations.NotNull;
import ru.batrdmi.svnplugin.SVNRevisionGraph;
import ru.batrdmi.svnplugin.logic.Revision;

import java.util.List;

public class CompareAction extends AnAction implements DumbAware {
    private final SVNRevisionGraph graph;

    public CompareAction(SVNRevisionGraph graph) {
        super("Compare with local", "Compare with local version", IconLoader.getIcon("/actions/diff.png"));
        this.graph = graph;
    }

    public void actionPerformed(@NotNull AnActionEvent ae) {
        List<Revision> revisions = ae.getData(SVNRevisionGraph.SELECTED_REVISIONS);
        int selectionSize = (revisions == null) ? 0 : revisions.size();
        if (selectionSize == 2) {
            graph.compareFileRevisions(revisions.get(0), revisions.get(1));
        } else if (selectionSize == 1) {
            Revision currentRevision = ae.getData(SVNRevisionGraph.CURRENT_REVISION);
            graph.compareFileRevisions(revisions.get(0), currentRevision);
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        List<Revision> selection = e.getData(SVNRevisionGraph.SELECTED_REVISIONS);
        FilePath filePath = e.getData(SVNRevisionGraph.SRC_FILE);
        int selectionSize = (selection == null) ? 0 : selection.size();
        Presentation p = e.getPresentation();
        if (selectionSize == 1) {
            p.setText("Compare with local");
            p.setDescription("Compare with local version");
        } else {
            p.setText("Compare");
            p.setDescription("Compare revisions");
        }
        boolean enabled = filePath != null && !filePath.isDirectory()
                && ((selectionSize == 1 && !selection.get(0).isDeleted())
                    || (selectionSize == 2 && !selection.get(0).isDeleted() && !selection.get(1).isDeleted()));
        p.setEnabled(enabled);
        if (ActionPlaces.isPopupPlace(e.getPlace())) {
            p.setVisible(enabled);
        }
    }
}
